package com.sdp.th.db.th_alarm_count.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdp.th.db.th_alarm_count.mapper.ThAlarmCountMapper;
import com.sdp.th.db.th_alarm_count.service.IThAlarmCountService;
import com.sdp.th.entity.ThAlarmCount;

/**
 * <p>
 * 报警数量 服务实现类
 * </p>
 *
 * @author zsp
 * @since 2025-04-17
 */
@Service
public class ThAlarmCountServiceImpl extends ServiceImpl<ThAlarmCountMapper, ThAlarmCount> implements IThAlarmCountService {

	private final Object lock = new Object();
	
	@Override
	public void setAlarmThCount(BigDecimal num) {
		synchronized (lock) {
			List<ThAlarmCount> li = list();
			if(li==null || li.size()==0) {
				ThAlarmCount count = new ThAlarmCount();
				count.setAlarmThCount(num);
				count.setAlarmTrendCount(BigDecimal.ZERO);
				count.setAlarmSmokeCount(BigDecimal.ZERO);
				save(count);
			}else {
				for(ThAlarmCount c : li) {
					BigDecimal dbNum = c.getAlarmThCount()==null?BigDecimal.ZERO:c.getAlarmThCount();
					c.setAlarmThCount(dbNum.add(num));
				}
				updateBatchById(li);
			}
		}
		
	}

	@Override
	public void setAlarmTrendCount(BigDecimal num) {
		synchronized (lock) {
			List<ThAlarmCount> li = list();
			if(li==null || li.size()==0) {
				ThAlarmCount count = new ThAlarmCount();
				count.setAlarmTrendCount(num);
				count.setAlarmThCount(BigDecimal.ZERO);
				count.setAlarmSmokeCount(BigDecimal.ZERO);
				save(count);
			}else {
				for(ThAlarmCount c : li) {
					BigDecimal dbNum = c.getAlarmTrendCount()==null?BigDecimal.ZERO:c.getAlarmTrendCount();
					c.setAlarmTrendCount(dbNum.add(num));
				}
				updateBatchById(li);
			}
		}
		
	}

	@Override
	public void setAlarmSmokeCount(BigDecimal num) {
		synchronized (lock) {
			List<ThAlarmCount> li = list();
			if(li==null || li.size()==0) {
				ThAlarmCount count = new ThAlarmCount();
				count.setAlarmSmokeCount(num);
				count.setAlarmThCount(BigDecimal.ZERO);
				count.setAlarmTrendCount(BigDecimal.ZERO);
				save(count);
			}else {
				for(ThAlarmCount c : li) {
					BigDecimal dbNum = c.getAlarmSmokeCount()==null?BigDecimal.ZERO:c.getAlarmSmokeCount();
					c.setAlarmSmokeCount(dbNum.add(num));
				}
				updateBatchById(li);
			}
		}
		
	}

	@Override
	public ThAlarmCount queryThAlarmCount() {
		LambdaQueryWrapper<ThAlarmCount> queryWrapper = new LambdaQueryWrapper<>();
		ThAlarmCount count = getOne(queryWrapper,false);
		if(count==null) {
			count = new ThAlarmCount();
			count.setAlarmThCount(BigDecimal.ZERO);
			count.setAlarmTrendCount(BigDecimal.ZERO);
			count.setAlarmSmokeCount(BigDecimal.ZERO);
		}
		return count;
	}

}
